//
//  FillOutCodeViewController.swift
//  Eternity
//
//  Created by cll12_12 on 2016/12/29.
//  Copyright © 2016年 ZhengWei. All rights reserved.
//

import UIKit

class FillOutCodeViewController: BaseViewController {

    var phoneNum: String!
    var timer: Timer?
    var timeCount = 59
    
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initBaseLayout()
        layoutPageSubviews()
        configUI()
        startTime()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - event response
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textField.resignFirstResponder()
    }
    
    override func leftItemAction(sender: UIButton) {
        _ = self.navigationController?.popViewController(animated: true)
    }
    
    func loginAction(sender: UIButton) {
        let userDefault = UserDefaults.standard
        userDefault.set(true, forKey: "loginStatus")
        userDefault.synchronize()
        self.dismiss(animated: true, completion: nil)
    }
    
    // MARK: - private method
    func initBaseLayout() {
        self.view.addSubview(messageLabel)
        self.view.addSubview(phoneLabel)
        self.view.addSubview(textField)
        self.view.addSubview(loginBtn)
    }
    
    func layoutPageSubviews() {
        messageLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.top.equalTo(self.view).offset(40)
            make.width.equalTo(86)
            make.height.equalTo(15)
        }
        
        phoneLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.top.equalTo(messageLabel.snp.bottom).offset(8)
            make.width.equalTo(170)
            make.height.equalTo(22)
        }
        
        textField.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(0)
            make.top.equalTo(phoneLabel.snp.bottom).offset(17)
            make.right.equalTo(self.view).offset(0)
            make.height.equalTo(48)
        }
        
        loginBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(14)
            make.top.equalTo(textField.snp.bottom).offset(34)
            make.right.equalTo(self.view).offset(-14)
            make.height.equalTo(44)
        }
        
    }
    
    func configUI() {
        self.view.backgroundColor = UIColor(hexString: "#EEEEEE")
        self.title = "填写验证码"
        initNavItem(controller: self, imageName: "nav_back_n", highlitedImageName: "nav_back_h", selectedImageName: "", isLeft: true)
        initNavItem(controller: self, imageName: "nav_rule_n", highlitedImageName: "nav_rule_h", selectedImageName: "", isLeft: false)
    }
    
    // 定时器启动
    func startTime() {
        // 开辟子线程启动定时器
        DispatchQueue.global(qos: .userInitiated).async {
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(FillOutCodeViewController.timeCountDown), userInfo: nil, repeats: true)
            RunLoop.current.run()
        }
        
    }
    
    // 获取验证码倒计时
    func timeCountDown() {
        weak var weakSelf = self
        DispatchQueue.main.async {
            weakSelf?.timeCount -= 1
            let button = weakSelf?.textField.rightBtn
            if weakSelf?.timeCount == 0 {
                button?.setTitle("重新发送", for: .normal)
                button?.isEnabled = true
                button?.setTitleColor(UIColor(hexString: "#252525"), for: .normal)
                weakSelf?.timer?.invalidate()
            } else {
                button?.setTitle(String(format: "%d秒后重发", (weakSelf?.timeCount)!), for: .normal)
                button?.isEnabled = false
                button?.setTitleColor(UIColor(hexString: "#CCCCCC"), for: .normal)
            }
        }
    }

    // MARK: - setters and getters
    var _messageLabel: UILabel!
    var messageLabel: UILabel {
        if _messageLabel == nil {
            _messageLabel = UILabel()
            _messageLabel.font = UIFont(name: "PingFangSC-Regular", size: 14)
            _messageLabel.textColor = UIColor(hexString: "#999999r")
            _messageLabel.textAlignment = .center
            _messageLabel.text = "已发送到手机"
        }
        return _messageLabel
    }
    
    var _phoneLabel: UILabel!
    var phoneLabel: UILabel {
        if _phoneLabel == nil {
            _phoneLabel = UILabel()
            _phoneLabel.font = UIFont(name: "PingFangSC-Medium", size: 22)
            _phoneLabel.textColor = UIColor(hexString: "#252525")
            _phoneLabel.textAlignment = .center
            
            let frontStr = phoneNum.substring(to: phoneNum.index(phoneNum.startIndex, offsetBy: 3))
            let middleStrRange = phoneNum.index(phoneNum.startIndex, offsetBy: 3)..<phoneNum.index(phoneNum.startIndex, offsetBy: 7)
            let middleStr = phoneNum.substring(with: middleStrRange)
            let laterStr = phoneNum.substring(from: phoneNum.index(phoneNum.startIndex, offsetBy: 7))
            
            _phoneLabel.text = "\(frontStr)" + "-" + "\(middleStr)" + "-" + "\(laterStr)"
        }
        return _phoneLabel
    }
    
    var _textField: CustomTextField!
    var textField: CustomTextField {
        if _textField == nil {
            _textField = CustomTextField()
            _textField.configUI(type: .LOGIN)
            _textField.delegate = self
            _textField.myDelegate = self
        }
        return _textField
    }
    
    var _loginBtn: UIButton!
    var loginBtn: UIButton {
        if _loginBtn == nil {
            _loginBtn = UIButton()
            _loginBtn.backgroundColor = UIColor(hexString: "#C5C5C5")
            _loginBtn.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 17)
            _loginBtn.setTitleColor(UIColor(hexString: "#FFFFFF"), for: .normal)
            _loginBtn.setTitle("登录", for: .normal)
            _loginBtn.isEnabled = false
            _loginBtn.addTarget(self, action: #selector(FillOutCodeViewController.loginAction(sender:)), for: .touchUpInside)
        }
        return _loginBtn
    }


}

extension FillOutCodeViewController: UITextFieldDelegate, CustomTextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if (textField.text?.characters.count)! >= 5 && string != "" {
            loginBtn.backgroundColor = UIColor(hexString: "#B7A18A")
            loginBtn.isEnabled = true
        } else if (textField.text?.characters.count)! < 12 {
            loginBtn.backgroundColor = UIColor(hexString: "#C5C5C5")
            loginBtn.isEnabled = false
        }
        
        if textField.text?.characters.count == 6 && string != "" {
            return false
        }
        
        if !string.isNumber() {
            if string == "" {
                return true
            }
            return false
        }
        return true
    }
    
    func resendAction(sender: UIButton) {
        timeCount = 60
        sender.isEnabled = false
        startTime()
    }
}

